<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义验证表单</title>
    <link href="../static/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body ng-app="test">
<div class="container" ng-controller="c1">
    <form name="myForm" class="form-horizontal">
        <div class="form-group">
            <label class="control-label">字段</label>
            <input class="form-control" name="termId" ng-model="termId" field required/>
        </div>
        <div class="alert alert-danger" ng-show="myForm.termId.$error.termIdExists">
            期号已经存在
        </div>
        <div class="alert alert-warning" ng-show="myForm.termId.$error.termIdChecking">
            验证中
        </div>
        <div class="alert alert-danger" ng-show="myForm.$invalid">
            表单验证失败
        </div>
    </form>
</div>
<script type="text/javascript" src="../static/lib/angular/angular.js"></script>
<script type="text/javascript">

    var requestUrl = "http://rapapi.org/mockjs/22290/api/backend-index/validate-term-id";

    angular
        .module("test", [])
        .controller("c1",["$scope",function ($scope) {
            $scope.termId = "";
        }])
        .directive("field", ["$http", "$timeout", function ($http, $timeout) {
            return {
                require: "ngModel",
                restrict: "A",
                link: function (scope, el, attrs, ctrl) {

                    var t;

                    scope.$watch(attrs.ngModel, function (newVal) {
                        // 没有编辑过,不验证
                        if(ctrl.$pristine) {
                            return;
                        }

                        ctrl.$setValidity("termIdChecking", false);
                        ctrl.$setValidity("termIdExists",true);

                        if (t) {
                            $timeout.cancel(t);
                        }

                        t = $timeout(function () {
                            $http({
                                url: requestUrl,
                                params: {
                                    termId: ctrl.$modelValue
                                }
                            }).then(function success(resp) {
                                ctrl.$setValidity("termIdExists", !resp.data.exists);
                                ctrl.$setValidity("termIdChecking",true);
                            })
                        },500);
                    });


                }
            }
        }]);
</script>
</body>
</html>